package com.zmy.xcx.controller;

import com.zmy.xcx.common.convention.result.Result;
import com.zmy.xcx.common.convention.result.Results;
import com.zmy.xcx.dao.entity.WxUser;
import com.zmy.xcx.pojo.dto.UserLoginDTO;
import com.zmy.xcx.pojo.vo.UserLoginVO;
import com.zmy.xcx.properties.JwtProperties;
import com.zmy.xcx.service.UserService;
import com.zmy.xcx.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/user")
@Slf4j
public class UserController {

    private final UserService userService;
    private final JwtProperties jwtProperties;
     @PostMapping("/login")
     public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
         log.info("用户登录入参:{}",userLoginDTO);
          //1.微信用户登录
         WxUser wxUser = userService.wxLogin(userLoginDTO);
          //2.生成jwt令牌
         Map<String,Object> claims =  new HashMap<>();
         claims.put("openid",wxUser.getOpenid());
         String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

         //3.返回用户信息
         UserLoginVO userLoginVO = new UserLoginVO().builder()
                 .openid(wxUser.getOpenid())
                 .token(token)
                 .build();
         return Results.success(userLoginVO);
     }
}
